package com.tangcl.module_commom.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.tangcl.module_base.log.LogUtils
import org.greenrobot.eventbus.EventBus

/**
 * Created by TCL on 2021/5/8
 *
 * description:Fragment基类
 */
abstract class BaseFragment : Fragment() {
    lateinit var mActivity: Activity
    private var mRootView: View? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        LogUtils.v(getTagName(),"onCreateView")
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false)
        }
        return mRootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData(arguments)
        initView()
        setListener()
    }

    /**
     * 是否注册EventBus
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected open fun isRegisterEventBus(): Boolean {
        return false
    }

    /**
     * Gets layout id.
     *
     * @return the layout id
     */
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化数据
     * 存取示例:
    fun newInstance(param1: String, param2: String) =
    XXXFragment().apply {
    arguments = Bundle().apply {
    putString(PARAM1, param1)
    putString(PARAM2, param2)
    }
    }

    arguments?.let {
    param1 = it.getString(ARG_PARAM1)
    param2 = it.getString(ARG_PARAM2)
    }
     */
    protected open fun initData(arguments: Bundle?) {}

    /**
     * view与数据绑定
     */
    protected open fun initView() {}

    /**
     * 设置监听
     */
    protected open fun setListener() {}

    override fun onResume() {
        super.onResume()
        if (isRegisterEventBus()) {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        LogUtils.v(getTagName(),"onDestroyView")
        if (isRegisterEventBus()) {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this)
            }
        }
    }

    protected open fun getTagName(): String {
        return this.javaClass.name
    }

}